<template>
  <el-form ref="formRef" :model="formData" :rules="rules" :disabled="disabled" label-width="140px" style="width: 100%">
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="立案号" prop="caseId">
          <el-select
            v-model="formData.caseId"
            :disabled="isFlow || disabled"
            placeholder="请选择立案号"
            clearable
            @change="handleCase">
            <el-option v-for="item in numberList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="当事人名称" prop="partyName">
          <el-input v-model="formData.partyName" disabled placeholder="请输入当事人名称" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="法定代表人" prop="legalRepresentative">
          <el-input v-model="formData.legalRepresentative" disabled placeholder="请输入法定代表人" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="统一社会信用代码" prop="creditCode">
          <el-input v-model="formData.creditCode" disabled placeholder="请输入统一社会信用代码" />
        </el-form-item>
      </el-col>
      <el-col :span="16">
        <el-form-item label="地址" prop="addressObj">
          <locationSelect v-model="formData.addressObj" disabled style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="8">
        <el-form-item label="处罚决定书文号" prop="decisionsNo">
          <el-input v-model="formData.decisionsNo" disabled placeholder="请输入行政处罚决定书文号" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="9">
        <el-form-item label="处罚决定内容(期限、金额)" prop="penaltyDuration" class="long-label">
          <el-date-picker
            v-model="formData.penaltyDuration"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择期限" />
          &nbsp;前
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item prop="penaltyAmount" label-width="0">
          <el-input-number
            v-model="formData.penaltyAmount"
            :min="0"
            controls-position="right"
            align="left"
            placeholder="请输入处罚金额"
            style="width: calc(100% - 40px); margin-right: 5px" />
          元整
        </el-form-item>
      </el-col>
      <el-col :span="9">
        <el-form-item label="被罚款人申请日期及理由" prop="applyDate" class="long-label">
          <el-date-picker
            v-model="formData.applyDate"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请日期" />
          &nbsp;前
        </el-form-item>
      </el-col>
      <el-col :span="7">
        <el-form-item prop="reason" label-width="0">
          <el-input v-model="formData.reason" placeholder="请输入申请理由" style="width: 100%" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="8">
        <el-form-item label="申请类型" prop="type">
          <el-radio-group v-model="formData.type" :disabled="isFlow || disabled" @change="handleTypeChange">
            <el-radio v-for="item in typeList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <template v-if="formData.type == '2'">
        <el-col :span="9">
          <el-form-item label="被罚款人申请(延期缴纳数额、期限)" prop="applyMattersDuration" class="long-label">
            <el-date-picker
              v-model="formData.applyMattersDuration"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              :disabled="isFlow || disabled"
              placeholder="请选择期限" />
            &nbsp;前
          </el-form-item>
        </el-col>
        <el-col :span="7">
          <el-form-item prop="applyMattersAmount" label-width="0">
            <el-input-number
              v-model="formData.applyMattersAmount"
              :min="0"
              :disabled="isFlow || disabled"
              controls-position="right"
              align="left"
              placeholder="请输入缴纳金额"
              style="width: calc(100% - 40px); margin-right: 5px" />
            元整
          </el-form-item>
        </el-col>
      </template>
      <template v-else-if="formData.type == '1'">
        <el-col :span="8">
          <el-form-item label="分期总额" prop="fineAmount">
            <el-input-number
              v-model="formData.fineAmount"
              controls-position="right"
              :disabled="isFlow || disabled"
              align="left"
              placeholder="请输入分期总额"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分期数" prop="installmentNum">
            <el-input-number
              v-model="formData.installmentNum"
              :min="2"
              controls-position="right"
              :disabled="isFlow || disabled"
              align="left"
              placeholder="请输入缴纳金额"
              style="width: 100%"
              @change="handleInstallmentNumChange" />
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="formData.installmentNum > 0">
          <el-form-item label="申请分期缴纳罚款详情" prop="installmentFineContentList">
            <el-table :data="formData.installmentFineContentList" border style="width: 100%">
              <el-table-column label="期数" width="80" align="center">
                <template #default="{ $index }">第{{ $index + 1 }}期</template>
              </el-table-column>
              <el-table-column label="缴纳期限" align="center">
                <template #default="{ row }">
                  <el-date-picker
                    v-model="row.duration"
                    type="date"
                    placeholder="请选择缴纳期限"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    :disabled="isFlow || disabled"
                    style="width: 100%"
                    @change="validateInstallmentData" />
                </template>
              </el-table-column>
              <el-table-column label="缴纳金额(元整)" align="center">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.amount"
                    :min="0"
                    :precision="2"
                    controls-position="right"
                    align="left"
                    :disabled="isFlow || disabled"
                    placeholder="请输入缴纳金额"
                    style="width: 100%"
                    @change="validateInstallmentData" />
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </template>
      <el-col :span="8">
        <el-form-item label="承办人是否同意" prop="isAgree">
          <el-radio-group v-model="formData.isAgree" :disabled="isFlow || disabled">
            <el-radio v-for="item in isAreeList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="承办人意见" prop="handlerOpinion">
          <el-input
            v-model="formData.handlerOpinion"
            type="textarea"
            :disabled="(isFlow && route?.query?.type !== 'refresh') || disabled"
            :rows="4"
            placeholder="请输入内容" />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup>
import { ref, nextTick, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getCaseList,
  getDecisionsList,
  getPenaltydeferralapply,
  addPenaltydeferralapply,
  updatePenaltydeferralapply,
  submitPenaltydeferralapply,
  todoItemReview,
  previewPdf,
} from '@/api/penalty/delayApproval'
import { registrationcaseDetail } from '@/api/filingReview/register'
import locationSelect from '@/components/locationSelect/index.vue'
import { ElMessage } from 'element-plus'

// 定义props
const props = defineProps({
  id: {
    type: String,
    default: '',
  },
  // 用于编辑时传入的id
  editId: {
    type: [String, Number],
    default: null,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  isFlow: {
    type: Boolean,
    default: false,
  },
})

const router = useRouter()
const route = useRoute()

const { proxy } = getCurrentInstance()
const emit = defineEmits(['handleSubmit'])

// 表单引用
const formRef = ref(null)

// 表单数据 - 使用computed来避免循环更新
const formData = ref({
  installmentNum: 2,
  installmentFineContentList: [
    { amount: null, duration: null },
    { amount: null, duration: null },
  ],
  type: '2',
  id: props.id,
})

// 案件列表
const numberList = ref([])

// 选项数据
const typeList = [
  { label: '分期', value: '1' },
  { label: '延期', value: '2' },
]
const isAreeList = [
  { label: '同意', value: '1' },
  { label: '拒绝', value: '2' },
]

// 自定义校验器：检查拍摄地点是否完整
const validateLocation = (rule, value, callback) => {
  if (!value || !value.streetOfPhotoLocation || !value.photoLocation) {
    callback(new Error('请选择拍摄地点'))
  } else {
    callback()
  }
}

// 自定义校验器：检查分期缴纳详情是否完整
const validateInstallmentList = (rule, value, callback) => {
  if (!value || value.length === 0) {
    callback(new Error('请至少添加一期分期缴纳信息'))
    return
  }

  for (let i = 0; i < value.length; i++) {
    const item = value[i]
    if (!item.amount || item.amount <= 0) {
      callback(new Error(`第${i + 1}期缴纳金额不能为空且必须大于0`))
      return
    }
    if (!item.duration) {
      callback(new Error(`第${i + 1}期缴纳期限不能为空`))
      return
    }
  }

  callback()
}

// 表单验证规则
const rules = {
  caseId: [{ required: true, message: '立案号不能为空', trigger: ['blur', 'change'] }],
  partyName: [{ required: true, message: '当事人名称不能为空', trigger: ['blur', 'change'] }],
  addressObj: [{ required: true, validator: validateLocation, trigger: ['blur', 'change'] }],
  creditCode: [{ required: true, message: '统一社会信用代码不能为空', trigger: ['blur', 'change'] }],
  legalRepresentative: [{ required: true, message: '法定代表人不能为空', trigger: ['blur', 'change'] }],
  decisionsNo: [{ required: true, message: '行政处罚决定书文号不能为空', trigger: ['blur', 'change'] }],
  penaltyDuration: [{ required: true, message: '罚款期限不能为空', trigger: ['blur', 'change'] }],
  penaltyAmount: [{ required: true, message: '罚款金额不能为空', trigger: ['blur', 'change'] }],
  applyDate: [{ required: true, message: '申请日期不能为空', trigger: ['blur', 'change'] }],
  reason: [{ required: true, message: '申请理由不能为空', trigger: ['blur', 'change'] }],
  type: [{ required: true, message: '申请类型不能为空', trigger: ['blur', 'change'] }],
  installmentNum: [{ required: true, message: '分期数不能为空', trigger: ['blur', 'change'] }],
  installmentFineContentList: [{ required: true, validator: validateInstallmentList, trigger: ['blur', 'change'] }],
  isAgree: [{ required: true, message: '是否同意延期不能为空', trigger: ['blur', 'change'] }],
  handlerOpinion: [{ required: true, message: '承办人意见不能为空', trigger: ['blur', 'change'] }],
}

// 获取案件列表
const handleCaseList = async () => {
  try {
    const res = await getCaseList()
    numberList.value = res.data.map(item => ({
      label: item.caseNo,
      value: item.id,
    }))
  } catch (error) {
    console.error('获取案件列表失败:', error)
  }
}

// 处理案件选择变化
const handleCase = async val => {
  if (!val) {
    formData.value = {
      partyName: '',
      legalRepresentative: '',
      businessType: '',
      creditCode: '',
      addressObj: {
        photoLocation: '',
        streetOfPhotoLocation: '',
      },
    }
    return
  }

  try {
    const res = await registrationcaseDetail(val)
    const res2 = await getDecisionsList(val)
    const {
      partyName,
      partyId,
      legalRepresentative,
      businessType,
      unifiedSocialCreditCode,
      streetOfCompanyAddress,
      address,
    } = res.data

    formData.value = {
      ...formData.value,
      caseNo: numberList.value.find(item => item.value === val)?.label || '',
      decisionsId: res2.data.id,
      decisionsNo: res2.data.decisionsNo,
      partyId: partyId,
      partyName: partyName,
      legalRepresentative: legalRepresentative,
      businessType: businessType,
      creditCode: unifiedSocialCreditCode,
      addressObj: {
        photoLocation: address,
        streetOfPhotoLocation: streetOfCompanyAddress,
      },
    }
  } catch (error) {
    console.error('获取案件详情失败:', error)
  }
}

// 处理申请类型变化
const handleTypeChange = value => {
  if (value === '1') {
    formData.value = {
      ...formData.value,
      applyMattersDuration: null,
      applyMattersAmount: null,
      installmentNum: 2,
      installmentFineContentList: [
        { amount: null, duration: null },
        { amount: null, duration: null },
      ],
    }
  } else if (value === '2') {
    formData.value = {
      ...formData.value,
      installmentNum: null,
      installmentFineContentList: [],
      applyMattersDuration: null,
      applyMattersAmount: null,
    }
  }
}

// 处理分期数变化
function handleInstallmentNumChange(value) {
  if (value > 0) {
    formData.value.installmentFineContentList = Array.from({ length: value }, () => ({
      amount: null,
      duration: null,
    }))
  } else {
    formData.value = {
      installmentFineContentList: [],
    }
  }
}
// 触发分期数据校验
function validateInstallmentData() {
  nextTick(() => {
    formRef.value?.validateField('installmentFineContentList')
  })
}

const handlePreview = () => {
  return new Promise(resolve => {
    submitForm(false, true)
      .then(async params => {
        previewPdf(params)
          .then(res => {
            if (!!res.msg) {
              window.open(res.msg)
              resolve()
            } else {
              ElMessage.warning('预览文件不存在')
              resolve()
            }
          })
          .catch(() => {
            ElMessage.warning('预览文件不存在')
            resolve()
          })
      })
      .catch(() => {
        ElMessage.warning('请先完善表单信息')
        resolve()
      })
  })
}

// 表单提交
const submitForm = (submitFlow = false, isPreview = false) => {
  return new Promise((resolve, reject) => {
    formRef.value
      .validate()
      .then(async () => {
        if (formData.value.type === '1') {
          let num = 0
          formData.value.installmentFineContentList.forEach(item => {
            if (item.amount) {
              num += parseFloat(item.amount)
            }
          })
          if (num !== formData.value.fineAmount) {
            ElMessage.error('分期总额与分期缴纳金额之和不一致')
            return
          }
        }

        // 处理地址数据
        const submitData = { ...formData.value }
        if (submitData.addressObj) {
          submitData.address = submitData.addressObj.photoLocation
          submitData.streetOfCompanyAddress = submitData.addressObj.streetOfPhotoLocation
        }

        if (isPreview === true) {
          resolve(submitData)
          return
        }

        if (submitFlow) {
          submitPenaltydeferralapply(submitData).then(response => {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            emit('handleSubmit')
          })
        } else {
          let submitApi = null
          if (submitData?.id && submitData.id.length > 0) {
            submitApi = updatePenaltydeferralapply
          } else {
            submitApi = addPenaltydeferralapply
          }
          submitApi(submitData).then(response => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            emit('handleSubmit')
          })
        }
      })
      .catch(() => {
        reject()
      })
  })
}

// 待办页面 提交 / 退回
const handleSubmitReview = async form => {
  if (route?.query?.type === 'refresh') {
    form.opinion = '同意'
  }
  await todoItemReview({
    ...form,
    // formFieldRevisionLogs: [],
    id: props.editId || props.id,
  })
  proxy.$modal.msgSuccess('操作成功')
  router.back()
}

// 待办页面获取批注列表
const timer = ref(null)
const getAnnotationList = () => {
  return new Promise((resolve, reject) => {
    timer.value = setInterval(() => {
      if (formData.value?.caseId?.length) {
        clearInterval(timer.value)
        resolve({ ...formData.value })
      } else {
        resolve([])
      }
    }, 500)
  })
}

// 暴露方法给父组件
defineExpose({
  formData,
  submitForm,
  handlePreview,
  handleSubmitReview,
  getAnnotationList,
  validate: () => formRef.value?.validate(),
  resetFields: () => formRef.value?.resetFields(),
  formRef,
})

// 获取详情数据
const loadDetailData = async id => {
  if (!id) return

  try {
    const response = await getPenaltydeferralapply(id)
    const detailData = response?.data
    if (!detailData) return
    // 处理地址数据格式
    if (detailData.address || detailData.streetOfCompanyAddress) {
      detailData.addressObj = {
        photoLocation: detailData.address || '',
        streetOfPhotoLocation: detailData.streetOfCompanyAddress || '',
      }
    }

    // 更新表单数据
    formData.value = { ...formData.value, ...detailData }
  } catch (error) {
    console.error('获取详情数据失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  handleCaseList()

  // 如果有editId或id中有id，则加载详情
  const id = props.editId || props.id
  if (id) {
    loadDetailData(id)
  }
})

onBeforeUnmount(() => {
  clearInterval(timer.value)
})
</script>

<style lang="scss" scoped></style>
